package com.wd.live.base.socket

import android.content.Context
import android.util.Log
import com.wd.live.base.socket.wsmanager.WsManager
import com.wd.live.base.socket.wsmanager.WsStatusListener
import okhttp3.OkHttpClient
import okhttp3.Response
import okio.ByteString
import java.util.concurrent.TimeUnit
import kotlin.math.log

class WebSocketUtils {
    interface OnMessageListener {
        fun message(msg: String?)
    }

    private var mOnMessageListener: OnMessageListener? = null
    fun setOnMessageListener(mOnMessageListener: OnMessageListener?) {
        this.mOnMessageListener = mOnMessageListener
    }

    private var mWsManager: WsManager? = null
    private var mNumber = 0
    private val mWsStatusListener: WsStatusListener = object : WsStatusListener() {
        override fun onOpen(response: Response?) {
            super.onOpen(response)
        }

        override fun onMessage(text: String?) {
            super.onMessage(text)
            mNumber++
            if (mNumber == 2) {
                mOnMessageListener?.message(text)
                mNumber = 0
            }
            //mOnMessageListener?.message("${mNumber}")
        }

        override fun onMessage(bytes: ByteString?) {
            super.onMessage(bytes)
        }

        override fun onReconnect() {
            super.onReconnect()
        }

        override fun onClosing(code: Int, reason: String?) {
            super.onClosing(code, reason)
        }

        override fun onClosed(code: Int, reason: String?) {
            super.onClosed(code, reason)
        }

        override fun onFailure(t: Throwable?, response: Response?) {
            super.onFailure(t, response)
        }
    }

    fun startConnect(url: String, context: Context?): WebSocketUtils {
        if (url.isNotEmpty() && url.contains("ws")) {
            if (mWsManager != null) {
                mWsManager!!.stopConnect()
                mWsManager = null
            }
            mWsManager = WsManager.Builder(context!!)
                .client(
                    OkHttpClient().newBuilder()
                        .pingInterval(15, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .build()
                )
                .needReconnect(true)
                .setReconnectInterval(3 * 1000) //设置重连步长(ms)
                .setReconnectIMaxTime((120 * 1000).toLong()) //设置重连最大时长
                .wsUrl(url)
                .build()
            mWsManager?.setWsStatusListener(mWsStatusListener)
            mWsManager?.startConnect()
        }
        return this
    }

    fun closeConnect() {
        mWsManager?.stopConnect()
        mWsManager = null
    }
}